<template>
  <div class="sku-form">
    <form-item-static label="规格">
      <div>
        <el-button
          v-if="false"
          type="primary"
          size="small"
          @click="onSaveSpecTemplate"
        >另存为模板</el-button>
        <el-button
          type="primary"
          size="small"
          @click="addPrivateSpec"
        >添加规格</el-button>
      </div>
      <div
        v-for="(attr, index) in privateGoodsItem"
        :key="index"
        class="sku-form__spec-container"
      >
        <el-form
          size="small"
          @submit.native.prevent
        >
          <el-form-item label="规格名">
            <div class="sku-form__spec-item">
              <el-input
                v-model="attr.spec"
                placeholder="请输入规格名"
                class="sku-form__spec-item__input"
              />
              <el-input
                v-if="attr.inputVisible"
                :ref="`saveTagInput${index}`"
                v-model="attr.inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="handleInputConfirm(attr.inputValue, attr)"
                @blur="handleInputConfirm(attr.inputValue, attr)"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(attr, index)"
              >添加</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox
              v-for="(tag, tindex) in attr.specValues"
              :key="tag.id"
              v-model="tag.checked"
              :label="tag.id"
            >
              <el-tag
                type="info"
                effect="plain"
                :closable="tag.editable"
                :disable-transitions="false"
                @close="handleClose(tag, tindex, attr)"
              >
                {{ tag.name }}
              </el-tag>
            </el-checkbox>
          </el-form-item>
        </el-form>
        <div
          v-if="attr.editable"
          class="spec-delete"
        >
          <el-link
            type="danger"
            @click="delPrivateSpec(index)"
          >删除规格</el-link>
        </div>
      </div>
    </form-item-static>
    <form-item-static label="价格 / 库存">
      <el-alert
        v-if="showTips"
        title="规格变动提醒"
        type="warning"
        description="取消或新增规格时将不继承原有规格商品的信息（包括销量、权重等指标数据）"
        show-icon
      />
      <el-form
        ref="dynamicSkuForm"
        :model="dynamicValidateForm"
        size="small"
      >
        <el-table
          ref="multipleTable"
          :data="tableBodyList"
          :span-method="objectSpanMethod"
          border
          size="small"
        >
          <el-table-column
            label="商品规格"
            align="center"
          >
            <el-table-column
              v-for="item in tableHeaderList"
              :key="item.prop"
              :label="item.propName"
              :property="item.prop"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.row[scope.column.property] }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column
            label="SKU图片"
            width="90"
            align="center"
          >
            <template slot-scope="scope">
              <uploader
                v-model="scope.row.thumb"
                :ratio="1"
                width="40px"
                type="image"
              />
            </template>
          </el-table-column>

          <el-table-column
            v-for="(item,aindex) in tableColumns"
            :key="aindex"
            :label="item.label"
            :property="item.name"
            :width="item.width?item.width:''"
            align="center"
          >
            <template
              slot="header"
              slot-scope="scope"
            >
              <span v-if="item.multi">
                <el-input
                  v-if="item.inputVisible"
                  :ref="`batchValueInput${item.name}`"
                  v-model="item.value"
                  :placeholder="'批量设置'+item.label"
                  size="small"
                  @keyup.enter.native="mutilInput(item)"
                  @blur="mutilInput(item)"
                />
                <span v-else>
                  <span>{{ item.label }}</span>
                  <el-button
                    type="text"
                    icon="el-icon-s-operation"
                    @click="showMutilInput(item, aindex, scope)"
                  />
                </span>
              </span>
              <span v-else>{{ item.label }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="scope.$index + '.'+item.name"
                :rules="item.rules"
                class="input-autosize"
              >
                <el-input
                  v-if="item.type==='number'"
                  :ref="`dynamicInput${scope.$index}.${item.name}`"
                  v-model.number="scope.row[item.name]"
                  :placeholder="scope.column.label"
                />
                <el-input-number
                  v-else-if="item.type==='float'"
                  :ref="`dynamicInput${scope.$index}.${item.name}`"
                  v-model="scope.row[item.name]"
                  :controls="false"
                  :min="0"
                  :step="0.01"
                  :placeholder="scope.column.label"
                />
                <el-input
                  v-else
                  :ref="`dynamicInput${scope.$index}.${item.name}`"
                  v-model="scope.row[item.name]"
                  :placeholder="scope.column.label"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="是否上架">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </form-item-static>
  </div>
</template>

<script>
import FormItemStatic from '@/components/Form/FormItemStatic'
import Uploader from '@/components/Uploader/index'
import { cartesianProduct } from '@/utils'
export default {
  name: 'SkuSpecForm',
  components: {
    FormItemStatic,
    Uploader
  },
  props: {
    value: {
      type: Object,
      default: null
    },
    skus: {
      type: Array,
      default: () => {
        return []
      }
    },
    specs: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    var numberValidator = (rule, value, callback) => {
      if (value !== '' && !/^[0-9]+.?[0-9]*/.test(value)) {
        callback(new Error('必须为数字类型'))
      } else {
        callback()
      }
    }
    return {
      tableColumns: [
        {
          name: 'subtitle',
          label: '副标题',
          multi: false,
          inputVisible: false,
          value: '',
          rules: []
        },
        {
          name: 'price',
          label: '价格（元）',
          multi: true,
          type: 'float',
          inputVisible: false,
          value: '',
          rules: [
            {
              required: true,
              message: '请设置商品价格',
              trigger: 'blur'
            },
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'market_price',
          label: '划线价（元）',
          multi: true,
          type: 'float',
          inputVisible: false,
          value: '',
          rules: [
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'weight',
          label: '重量（kg）',
          multi: true,
          type: 'float',
          inputVisible: false,
          value: '',
          rules: [
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'volume',
          label: '体积（m³）',
          multi: true,
          type: 'float',
          inputVisible: false,
          value: '',
          rules: [
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'stock',
          label: '库存',
          multi: true,
          type: 'number',
          inputVisible: false,
          value: '',
          rules: [
            { required: true, message: '请设置商品库存', trigger: 'blur' },
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'lowstock',
          label: '库存预警',
          multi: true,
          type: 'number',
          inputVisible: false,
          value: '',
          rules: [
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'min',
          label: '起订量',
          multi: true,
          type: 'number',
          inputVisible: false,
          value: '',
          rules: [
            {
              validator: numberValidator,
              trigger: 'blur'
            }
          ]
        },
        {
          name: 'goods_no',
          label: '商品编码',
          multi: true,
          inputVisible: false,
          value: '',
          rules: [{ max: 18, message: '最多18位字符', trigger: 'blur' }]
        }
      ],
      dynamicValidateForm: {},
      tableHeaderList: [],
      tableBodyList: [],
      privateGoodsItem: []
    }
  },
  computed: {
    formData: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', ...val)
      }
    },
    goods() {
      return this.skus
    },
    specItems() {
      const specs = this.specs
      const skus = this.skus
      var checkedSpecValues = []
      for (var i = 0; i < skus.length; i++) {
        var item = skus[i]
        if (item.hidden) {
          continue
        }
        checkedSpecValues = checkedSpecValues.concat(...item.kvs.split(';'))
      }
      return specs.map(item => {
        var values = item.values.map(v => {
          return {
            id: v.id,
            name: v.value,
            spec_id: v.spec_id,
            editable: v.editable,
            checked: checkedSpecValues.indexOf(v.spec_id + ':' + v.id) !== -1
          }
        })
        return {
          id: item.id,
          spec: item.name,
          specValues: values,
          editable: item.editable,
          inputVisible: false,
          inputValue: ''
        }
      })
    },
    showTips() {
      return (
        this.goods.length > 0 &&
        !this.tableBodyList.find(item => {
          return item.id > 0
        })
      )
    },
    // 计算规格
    calculateAttribute() {
      return this.privateGoodsItem.filter(item => {
        var values = item.specValues.filter(v => {
          return v.checked
        })
        return item.spec && values.length > 0
      })
    }
  },
  watch: {
    // 监听规格数据
    calculateAttribute(newVal) {
      this.formatTableData(newVal)
    },
    // 监听规格数据
    tableBodyList: {
      handler: function(newVal) {
        console.log('tableBodyList changed')
        this.formData.skus = [...newVal]
      },
      deep: true
    },
    // 监听规格数据
    privateGoodsItem: {
      handler(newVal) {
        console.log('privateGoodsItem changed')
        this.formData.specs = [...newVal]
      },
      deep: true
    }
  },
  created() {
    console.log('SkuSpecForm created')
    this.privateGoodsItem = this.specItems
  },
  methods: {
    onSubmit() {
      this.$refs['dynamicSkuForm'].validate(valid => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    submit() {
      const data = Object.assign(
        {},
        {
          title: '',
          skus: this.tableBodyList,
          specs: this.privateGoodsItem
        }
      )
      this.$http.commodity.updateSku(data, this.value).then(res => {
        console.log(res)
        this.goBack()
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      var theads = this.tableHeaderList
      if (theads.length < 2 || columnIndex + 1 >= theads.length) {
        return
      } else {
        var columns = theads.filter((item, index) => {
          return index > columnIndex
        })
        var max = 1
        for (var i = 0; i < columns.length; i++) {
          max *= columns[i].count
        }
        if (max < 2) {
          return
        } else {
          if (rowIndex % max === 0) {
            return {
              rowspan: max,
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      }
    },
    formatTableData(newVal) {
      const cloneNewVal = newVal
      const attrId = [] // 规格ID数组
      const attrName = [] // 规格名数组
      const attrValue = [] // 规格值数组
      var tableHeaderList = []
      for (var i = 0; i < cloneNewVal.length; i++) {
        var item = cloneNewVal[i]
        var checkedSpecs = item.specValues.filter(v => {
          return v.checked
        })
        if (!checkedSpecs.length) {
          continue
        }
        attrId.push(item.id)
        attrName.push(item.spec)
        attrValue.push(checkedSpecs)
        tableHeaderList.push({
          prop: item.spec,
          propName: item.spec,
          count: checkedSpecs.length
        })
      }
      // 表头
      this.tableHeaderList = tableHeaderList

      // 表格内容数据（笛卡尔积算法）
      const finalArr = cartesianProduct(...attrValue)
      // 表格内容
      var formData = {}
      this.tableBodyList = this.formatSpecItems(finalArr, attrName, formData) // 表格内容数据
      this.dynamicValidateForm = formData
    },
    formatSpecItems(data, attrName, formData) {
      var kvsIds = []
      return data.map((item, index) => {
        const obj = {
          id: 0,
          status: true,
          thumb: '',
          goods_no: '',
          subtitle: '',
          price: '',
          market_price: '',
          stock: '',
          weight: '',
          volume: '',
          lowstock: 0,
          min: 0,
          // max_credit: 0,
          specs: []
        }
        var kvs = []
        for (let i = 0; i < item.length; i++) {
          var specId = item[i].spec_id + ''
          var specValueId = item[i].id + ''
          if (specId.indexOf('d_') === -1 && specValueId.indexOf('v_') === -1) {
            kvs.push(specId + ':' + specValueId)
          }
          obj[attrName[i]] = item[i].name
          obj.specs.push({
            spec_id: specId,
            spec_value_id: specValueId,
            spec_name: attrName[i],
            spec_value: item[i].name,
            unchecked: !item[i].checked
          })
        }
        var _kvs = kvs.join(';')
        console.log('_kvs', _kvs)
        console.log('goods', this.goods)
        if (kvs) {
          var goods = this.goods.find(item => {
            return _kvs.indexOf(item.kvs) !== -1
          })
          if (goods) {
            console.log('kvsids unset goods:', kvsIds, !kvsIds.includes(goods.id))
            if (!kvsIds.includes(goods.id)) {
              kvsIds.push(goods.id)
              obj.id = goods.id
            }
            obj.thumb = goods.thumb
            obj.price = goods.price
            obj.subtitle = goods.subtitle
            obj.market_price = goods.market_price
            obj.stock = goods.stock
            obj.weight = goods.weight
            obj.volume = goods.volume
            obj.min = goods.min
            // obj.max_credit = goods.max_credit
            obj.lowstock = goods.lowstock
            obj.status = goods.status
          }
          console.log('kvs update obj', obj)
        }
        console.log('new obj', obj)
        formData[index] = obj
        return obj
      })
    },
    // 添加规格
    addPrivateSpec() {
      const that = this
      var index = that.privateGoodsItem.length
      var item = {
        id: 'd_' + index,
        spec: '',
        editable: true,
        specValues: [],
        inputVisible: false,
        inputValue: ''
      }
      this.$set(that.privateGoodsItem, index, item)
    },
    onSaveSpecTemplate() {},
    delPrivateSpec(index) {
      this.privateGoodsItem.splice(index, 1)
    },
    toggleFormValidate() {
      var validated = false
      this.$refs['dynamicSkuForm'].validate((valid, obj) => {
        if (valid) {
          validated = true
        } else {
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `dynamicInput${i}`
            break
          }
          var dom = this.$refs[firstErrorElname][0]
          if (dom) {
            dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          return false
        }
      })
      return validated
    },
    handleInputConfirm(val, attr) {
      var exisit = attr.specValues.find(item => {
        return item.name === val
      })
      if (val && !exisit) {
        var index = attr.specValues.length + 1
        attr.specValues.push({
          id: 'v_' + index,
          spec_id: attr.id,
          name: val,
          editable: true,
          checked: true
        })
      }
      attr.inputVisible = false
      attr.inputValue = ''
    },
    handleClose(tag, index, item) {
      if (tag.editable) {
        item.specValues.splice(index, 1)
      }
    },
    showInput(attr, index) {
      attr.inputVisible = true
      this.$set(this.privateGoodsItem, index, attr)
      this.$nextTick(_ => {
        this.$refs[`saveTagInput${index}`][0].$refs.input.focus()
      })
    },
    showMutilInput(attr, index) {
      attr.inputVisible = true
      this.$nextTick(_ => {
        var refname = 'batchValueInput' + attr.name
        this.$refs[refname][0].$refs.input.focus()
      })
    },
    mutilInput(attr, val, name) {
      const value = attr.value
      if (value) {
        var skus = this.tableBodyList
        for (var i = 0; i < skus.length; i++) {
          var sku = skus[i]
          sku[attr.name] = value
        }
      }
      attr.inputVisible = false
      attr.value = ''
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox {
  margin-right: 0;
  &__input {
    display: none;
  }
  .el-checkbox__input.is-checked + .el-checkbox__label {
    .el-tag {
      color: red;
      background-color: #e8f4ff;
      color: #1890ff;
      border: 1px solid #d1e9ff;
    }
  }
}
.em-card__body {
  padding-left: 0;
  padding-right: 0;
}

.sku-form {
  &__spec-container {
    position: relative;
    margin-top: 10px;
    padding: 15px 15px 0;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fcfcfc;
    & + & {
      margin-top: 15px;
    }
    .el-input--medium {
      width: 60%;
    }
    .el-tag {
      margin-right: 10px;
    }
    .input-new-tag {
      width: 90px;
      margin-right: 10px;
      vertical-align: bottom;
    }
    .spec-delete {
      position: absolute;
      right: 5px;
      top: 5px;
    }
  }
  &__spec-item {
    display: flex;
    &__input {
      width: 260px;
      margin-right: 12px;
    }
  }
  .input-autosize {
    .el-input-number {
      width: auto;
    }
  }
}

::v-deep .el-table tbody tr:hover > td {
  background-color: transparent;
}
</style>
